/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * DialogAddReceipt.java
 *
 * Created on Feb 1, 2012, 5:23:20 PM
 */
package GUI;

import Entity.Category;
import Entity.ConnectionSQL;
import Entity.Item;
import Entity.Receipt;
import Entity.User;
import java.util.List;
import java.util.ResourceBundle;
import javax.swing.JOptionPane;
import javax.swing.SpinnerNumberModel;

/**
 *
 * @author Trung Duc
 */
public class DialogAddReceipt extends javax.swing.JDialog {
    private User user;
    private ResourceBundle messages;
    private boolean checkBillID;
    private boolean checkItemName;
    private GUI.PanelReceipt parent;
    /** Creates new form DialogAddReceipt */
    public DialogAddReceipt(GUI.PanelReceipt parent, boolean modal,User user,ResourceBundle messages) {
        //super(parent, modal);
        initComponents();
        this.user = user;
        this.messages = messages;
        this.parent = parent;
        ConnectionSQL cnn = new ConnectionSQL(messages);
        List<Category> listCategory = cnn.getCategory();
        lblBillID.setText("");
        lblItemName.setText("");
        setComboBoxCategory(listCategory);
        checkBillID = false;
        checkItemName = false;
        this.setLocationRelativeTo(parent);
    }
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        txtItemName = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        cbbCategory = new javax.swing.JComboBox();
        jLabel4 = new javax.swing.JLabel();
        btnOK = new javax.swing.JButton();
        btnCancel = new javax.swing.JButton();
        txtBillID = new javax.swing.JFormattedTextField();
        lblBillID = new javax.swing.JLabel();
        lblItemName = new javax.swing.JLabel();
        txtQuantity = new javax.swing.JFormattedTextField();
        jLabel5 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        jLabel1.setText("Bill ID: ");

        jLabel2.setText("Item Name:");

        txtItemName.addCaretListener(new javax.swing.event.CaretListener() {
            public void caretUpdate(javax.swing.event.CaretEvent evt) {
                txtItemNameCaretUpdate(evt);
            }
        });

        jLabel3.setText("Category: ");

        cbbCategory.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));

        jLabel4.setText("Quantity: ");

        btnOK.setText("OK");
        btnOK.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnOKActionPerformed(evt);
            }
        });

        btnCancel.setText("Cancel");
        btnCancel.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCancelActionPerformed(evt);
            }
        });

        txtBillID.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.NumberFormatter(new java.text.DecimalFormat("####"))));
        txtBillID.addCaretListener(new javax.swing.event.CaretListener() {
            public void caretUpdate(javax.swing.event.CaretEvent evt) {
                txtBillIDCaretUpdate(evt);
            }
        });

        lblBillID.setForeground(new java.awt.Color(255, 0, 0));
        lblBillID.setText("jLabel5");

        lblItemName.setForeground(new java.awt.Color(255, 0, 0));
        lblItemName.setText("jLabel6");

        txtQuantity.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.NumberFormatter(new java.text.DecimalFormat("#####"))));

        jLabel5.setFont(new java.awt.Font("Tahoma", 1, 20)); // NOI18N
        jLabel5.setText("Receipt");

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(52, 52, 52)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 45, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel2)
                            .addComponent(jLabel3)
                            .addComponent(jLabel4))
                        .addGap(22, 22, 22)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(txtQuantity, javax.swing.GroupLayout.DEFAULT_SIZE, 158, Short.MAX_VALUE)
                            .addComponent(txtBillID, javax.swing.GroupLayout.DEFAULT_SIZE, 158, Short.MAX_VALUE)
                            .addComponent(cbbCategory, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(txtItemName, javax.swing.GroupLayout.DEFAULT_SIZE, 158, Short.MAX_VALUE)
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addComponent(btnOK)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 46, Short.MAX_VALUE)
                                .addComponent(btnCancel)))
                        .addGap(18, 18, 18)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(lblItemName, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(lblBillID, javax.swing.GroupLayout.DEFAULT_SIZE, 100, Short.MAX_VALUE)))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(159, 159, 159)
                        .addComponent(jLabel5, javax.swing.GroupLayout.PREFERRED_SIZE, 93, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel5, javax.swing.GroupLayout.PREFERRED_SIZE, 26, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(11, 11, 11)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(txtBillID, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(lblBillID))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(txtItemName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(lblItemName))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(cbbCategory, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(txtQuantity, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 28, Short.MAX_VALUE)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnOK)
                    .addComponent(btnCancel))
                .addGap(19, 19, 19))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnOKActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnOKActionPerformed
        ok();
    }//GEN-LAST:event_btnOKActionPerformed

    private void txtBillIDCaretUpdate(javax.swing.event.CaretEvent evt) {//GEN-FIRST:event_txtBillIDCaretUpdate
        try{
            checkBillID(Integer.parseInt(txtBillID.getText()));
        }catch(Exception e){
            checkBillID(-1);
        }
    }//GEN-LAST:event_txtBillIDCaretUpdate

    private void txtItemNameCaretUpdate(javax.swing.event.CaretEvent evt) {//GEN-FIRST:event_txtItemNameCaretUpdate
         checkItemName(txtItemName.getText());
    }//GEN-LAST:event_txtItemNameCaretUpdate

    private void btnCancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancelActionPerformed
        this.dispose();
    }//GEN-LAST:event_btnCancelActionPerformed

    /**
     * @param args the command line arguments
     */

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnCancel;
    private javax.swing.JButton btnOK;
    private javax.swing.JComboBox cbbCategory;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JLabel lblBillID;
    private javax.swing.JLabel lblItemName;
    private javax.swing.JFormattedTextField txtBillID;
    private javax.swing.JTextField txtItemName;
    private javax.swing.JFormattedTextField txtQuantity;
    // End of variables declaration//GEN-END:variables

    private void setComboBoxCategory(List<Category> listCategory){
        cbbCategory.removeAllItems();
        for(Category c : listCategory){
            cbbCategory.addItem(c.getName());
        }
    }
    private void checkBillID(int billID) {
        ConnectionSQL cnn = new ConnectionSQL(messages);
        if(!cnn.checkBillID(billID)){ 
            lblBillID.setText(messages.getString("billIDInvalid"));
            checkBillID = false;
        }
        else {
            checkBillID = true;
            lblBillID.setText("");
            if(checkItemName){
               setComboBoxCategory(cnn.getCategoryByItemNameAndBillID(txtItemName.getText(),billID));
            }
        }
    }

    private void checkItemName(String itemName) {
        ConnectionSQL cnn = new ConnectionSQL(messages);
        int id =-1;
        if(checkBillID) id = Integer.parseInt(txtBillID.getText());
        if(!cnn.checkItemNameInBill(itemName,id)){
            lblItemName.setText(messages.getString("itemNameInvalid"));
            checkItemName = false;
        }
        else{
            lblItemName.setText("");
            checkItemName = true;
            if(checkBillID)
            setComboBoxCategory(cnn.getCategoryByItemNameAndBillID(itemName,Integer.parseInt(txtBillID.getText())));
        }
    }

    private void ok() {
        if(checkBillID && checkItemName && !txtQuantity.getText().equals("")){
            ConnectionSQL cnn = new ConnectionSQL(messages);
            int billID = Integer.parseInt(txtBillID.getText());
            Item item = cnn.getItemByItemNameAndCategoryName(txtItemName.getText(), cbbCategory.getSelectedItem().toString());
            int quantityBillDetail = cnn.getQuantityBillDetail(item.getId(), billID);
            int quantity = Integer.parseInt(txtQuantity.getText());
            if(quantity > quantityBillDetail || quantity <= 0){
                JOptionPane.showMessageDialog(this, messages.getString("messagesOverQuantity"));
            }
            else {
                Receipt receiptCheck = cnn.getReceiptByBilIDAndItemID(billID, item.getId());
                if(receiptCheck!=null){
                   JOptionPane.showMessageDialog(this, messages.getString("messagesReceiptExist"));
                }else{
                int choice = JOptionPane.showConfirmDialog(this, messages.getString("messagesCreateReceipt"),messages.getString("titleConfirmCreateReceipt"), JOptionPane.YES_NO_OPTION);
                if(choice== JOptionPane.YES_OPTION){
                    Receipt receipt = new Receipt(billID,item.getId(),user.getId(),quantity);
                    if(cnn.addReceipt(receipt))
                    JOptionPane.showMessageDialog(this, messages.getString("messagesAddReceiptComplete"));
                    parent.viewAllReceipt();
                    this.dispose();
                        }else{
                    JOptionPane.showMessageDialog(this, messages.getString("messagesAddReceiptError"));
                }
            }
            }
        }else{
            JOptionPane.showMessageDialog(this, messages.getString("messagesAddReceiptNotValid"));
        }
    
    }
}
